package udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class EchoClient01 {
    private DatagramSocket socket =null;
    private String serverIp;
    private int serverPort;

    public EchoClient01(String serverIp, int serverPort) throws SocketException{
        this.serverIp=serverIp;
        this.serverPort=serverPort;
        socket=new DatagramSocket();
    }

    public void start() throws IOException{
        System.out.println("客户端启动");
        Scanner scanner=new Scanner(System.in);
        
        while(true){
        //读取用户输入内容
        System.out.print(">");
        String request=scanner.next();
        //构造udp请求，并发送，不光要填内容，还要端口和ip
        DatagramPacket reqPacket=new DatagramPacket(request.getBytes(),request.getBytes().length,
                                 InetAddress.getByName(serverIp),serverPort);

        //读取响应
        DatagramPacket respPacket=new DatagramPacket(new byte[4096], 4096);
        socket.receive(respPacket);
        String response=new String(respPacket.getData(),0,respPacket.getLength());
        //显示响应内容
        System.out.println(response);
        }
       
    }

    public static void main(String[] args) throws Exception {
        EchoClient01 echoClient01=new EchoClient01("127.0.0.1", 4060);
        echoClient01.start();
    }



}
